//
//  AMapViewController.m
//  SeaChat
//
//  Created by dllo on 16/6/17.
//  Copyright © 2016年 潘强. All rights reserved.
//

#import "AMapViewController.h"

#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

#import <iflyMSC/iflyMSC.h>


static NSString *cellIdentifier = @"cellIdentifier";
static NSString *annotationIndetifier = @"annotationReuseIndetifier";

@interface AMapViewController ()<MAMapViewDelegate,AMapSearchDelegate,UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,UITextFieldDelegate,IFlyRecognizerViewDelegate>

@property(nonatomic,retain)MAMapView *mapView;//地图对象
@property(nonatomic,retain)UIButton *locationButton;//定位button
@property(nonatomic,retain)AMapSearchAPI *search;//地图搜索对象
@property(nonatomic,retain)UITextField *searchTextField;//设置搜索框

@property(nonatomic,assign)CGFloat currentZoomlevel;//当前

@property(nonatomic,retain)CLLocation *currentlocation;//接收当前位置信息
@property(nonatomic,retain)UITableView *resultTableview;//附近搜索结果tableview
@property(nonatomic,retain)NSArray *poisArray;//搜索结果数组
@property(nonatomic,retain)UILongPressGestureRecognizer *longPress;
@property(nonatomic,retain)MAPointAnnotation *destinationPoint;//目的地大头针
@property(nonatomic,assign)BOOL isSelectUser;//表明点击标注的种类
@property(nonatomic,retain)NSArray *pathPolylines;//路线规划数组

@property(nonatomic,retain)IFlyRecognizerView *iflyRecognizerView;


@end

@implementation AMapViewController

-(void)dealloc{
    [_mapView release];
    [_locationButton release];
    [_search release];
    [_currentlocation release];
    [_resultTableview release];
    [_poisArray release];
    [_longPress release];
    [_destinationPoint release];
    [_pathPolylines release];
    [_searchTextField release];
    [_iflyRecognizerView release];
    
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initMapView];
    [self initLocationButton];
    [self initZoomButton];
    [self initSearch];
    [self initSearchBtn];
    [self initTableView];
   [self initAttributes];
    [self initPathBtn];
    
//设置语音key
    NSString *appid = @"5762948f";
    NSString *initString = [NSString stringWithFormat:@"appid=%@",appid];
    [IFlySpeechUtility createUtility:initString];
    
    [self initIfly];
    

    
    
    // Do any additional setup after loading the view.
}

//设置mapView
-(void)initMapView{
self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 60, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 60)];
    
    self.mapView.delegate = self;
    //罗盘位置
    self.mapView.compassOrigin = CGPointMake(self.mapView.compassOrigin.x, self.mapView.compassOrigin.y);
    //比例尺位置
    self.mapView.scaleOrigin = CGPointMake(self.mapView.scaleOrigin.x, self.view.frame.size.height - 40);
    [self.view addSubview:self.mapView];
    [self.mapView release];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.mapView addGestureRecognizer:tap];
    tap.delegate = self;
    [tap release];
    
    
    
    self.currentZoomlevel = 16.2;//(3 - 19)
    //设置缩放级别
    [self.mapView setZoomLevel:self.currentZoomlevel animated:NO];
    //打开用户定位
    self.mapView.showsUserLocation = YES;
    
    //设置跟踪模式
   
    [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    

}

//创建查询对像及搜索框 返回按钮
-(void)initSearch{
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    //搜索框
    self.searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(50, 25, self.view.frame.size.width / 5 * 3, 35)];
    self.searchTextField.placeholder = @"搜索附近的地点";
    self.searchTextField.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.searchTextField.layer.borderWidth = 1;
    self.searchTextField.layer.masksToBounds = YES;
    self.searchTextField.layer.cornerRadius = 10;
    self.searchTextField.backgroundColor = [UIColor whiteColor];
    self.searchTextField.clearsOnBeginEditing = YES;
    self.searchTextField.delegate = self;
    [self.view addSubview:self.searchTextField];
    [self.searchTextField release];
    
    //返回按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(5, self.searchTextField.frame.origin.y + 5, 40, 30);
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    backButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [backButton addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    
    //语音按钮
    UIButton *voiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    voiceButton.frame = CGRectMake(CGRectGetMaxX(self.searchTextField.bounds) + 18, self.searchTextField.frame.origin.y + 5, 28, self.searchTextField.frame.size.height - 10);
    [voiceButton setImage:[UIImage imageNamed:@"voice"] forState:UIControlStateNormal];
   // [voiceButton setImage:[UIImage imageNamed:@"voicePush"] forState:UIControlStateHighlighted];
    [voiceButton addTarget:self action:@selector(voiceButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    voiceButton.adjustsImageWhenHighlighted = NO;
    
    
    [self.view addSubview:voiceButton];

    
}

-(void)initIfly{
    //1.创建语音听写对象
    self.iflyRecognizerView = [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
    self.iflyRecognizerView.delegate = self;
    //设置听写模式
    [self.iflyRecognizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    //设置是否返回标点符号
    [_iflyRecognizerView setParameter:@"0" forKey:[IFlySpeechConstant ASR_PTT]];
    
    //设置音频来源为麦克风
    [_iflyRecognizerView setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
    
    //设置听写结果格式为plain  默认json
    [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];

    
    [self.view addSubview:self.iflyRecognizerView];
    self.iflyRecognizerView.hidden = YES;
    [_iflyRecognizerView release];

}



//语音按钮点击
-(void)voiceButtonAction{
    
    [self.searchTextField resignFirstResponder];
    
    self.iflyRecognizerView.hidden = NO;
    
//启动识别
    [self.iflyRecognizerView start];
}

/*识别结果返回代理
 @param resultArray 识别结果
 @ param isLast 表示是否最后一次结果
 */
-(void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast{
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    
    self.searchTextField.text = [NSString stringWithFormat:@"%@%@",self.searchTextField.text,result];

}

/*识别会话错误返回代理
 @ param  error 错误码
 */

-(void)onError:(IFlySpeechError *)error{
    NSLog(@"科大讯飞听写错误:%@",error);

}

//返回按钮点击
-(void)backButtonAction{
[self dismissViewControllerAnimated:YES completion:^{
    
    
}];

}

/**
 *  3.允许多个手势识别器共同识别
 
 默认情况下，两个gesture recognizers不会同时识别它们的手势,但是你可以实现UIGestureRecognizerDelegate协议中的
 gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:方法对其进行控制。这个方法一般在一个手    势接收者要阻止另外一个手势接收自己的消息的时候调用，如果返回YES,则两个gesture recognizers可同时识别，如果返回NO，则     并不保证两个gesture recognizers必不能同时识别，因为另外一个gesture recognizer的此方法可能返回YES。也就是说两个
 gesture recognizers的delegate方法只要任意一个返回YES，则这两个就可以同时识别；只有两个都返回NO的时候，才是互斥的。默认情况下是返回NO。
 *  如果不写这句话，会导致自己创建的手势不会响应事件，因为webView里的子控件自带很多手势。
 *  @param gestureRecognizer      手势
 *  @param otherGestureRecognizer 其他手势
 *
 *  @return YES代表可以多个手势同时识别，默认是NO，不可以多个手势同时识别
 */

//地图添加触摸方法
-(void)tapAction:(UITapGestureRecognizer *)tap{
    if (![tap.view isKindOfClass:[MAAnnotationView class]]) {
        [self.searchTextField resignFirstResponder];
        self.resultTableview.hidden = YES;
    }
    
}


-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}




-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


//当位置更新时，会进定位回调，通过回调函数，能获取到定位点的经纬度坐标
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    if (updatingLocation) {

        self.currentlocation = [userLocation.location copy];
        
    }
}


//逆地理编码 发起搜索请求
-(void)reGeoAction{
    //用户当前坐标
    if (self.currentlocation && self.isSelectUser == YES) {
        AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude:self.currentlocation.coordinate.latitude longitude:self.currentlocation.coordinate.longitude];
        [self.search AMapReGoecodeSearch:request];
        [request release];
    }
    
    //长按手势目的地
    if (self.destinationPoint && self.isSelectUser == NO) {
        AMapReGeocodeSearchRequest *requestDes = [[AMapReGeocodeSearchRequest alloc] init];
        requestDes.location = [AMapGeoPoint locationWithLatitude:self.destinationPoint.coordinate.latitude longitude:self.destinationPoint.coordinate.longitude];
        [self.search AMapReGoecodeSearch:requestDes];
        [requestDes release];
    }
    
}

//逆地理查询完成,获取搜索结果
-(void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response{
    
    if (self.isSelectUser == YES) {
        NSString *title = response.regeocode.addressComponent.city;
        if (title.length == 0) {
            title = response.regeocode.addressComponent.province;
        }
        self.mapView.userLocation.title = title;
        self.mapView.userLocation.subtitle = response.regeocode.formattedAddress;
        
    } else {
        NSString *title = response.regeocode.addressComponent.city;
        if (title.length == 0) {
            title = response.regeocode.addressComponent.province;
        }
        self.destinationPoint.title = title;
        self.destinationPoint.subtitle = response.regeocode.formattedAddress;
    }
}

//在选中用户位置annotation时弹出当前地址
-(void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    // 选中定位annotation的时候进行逆地理编码查询
    if ([view.annotation isKindOfClass:[MAUserLocation class]]) {
        self.isSelectUser = YES;
        [self reGeoAction];
    }
    
    if ([view.annotation isKindOfClass:[MAPointAnnotation class]])
    {
        self.isSelectUser = NO;
        [self reGeoAction];
    }
}

//创建放大缩小按钮
-(void)initZoomButton{
    UIButton *zoomLargeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.mapView addSubview:zoomLargeBtn];
//    [zoomLargeBtn setTitle:@"放大" forState:UIControlStateNormal];
//    [zoomLargeBtn setTitleColor:[UIColor blueColor] forState: UIControlStateNormal];
   // zoomLargeBtn.frame = CGRectMake(self.mapView.compassOrigin.x, CGRectGetMidY(self.mapView.bounds) + 30, 40, 30);
    
    [zoomLargeBtn makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.top.mas_equalTo(self.locationButton).offset(-40);
        make.left.mas_equalTo(self.mapView.compassOrigin.x);
        
    }];
    
    [zoomLargeBtn setImage:[UIImage imageNamed:@"zoomLarge"] forState:UIControlStateNormal];
    zoomLargeBtn.backgroundColor = [UIColor whiteColor];
    
    [zoomLargeBtn addTarget:self action:@selector(zoomButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    zoomLargeBtn.tag = 1000;
    
    
    
    UIButton *zoomSmallBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.mapView addSubview:zoomSmallBtn];

//    [zoomSmallBtn setTitle:@"缩小" forState:UIControlStateNormal];
//    [zoomSmallBtn setTitleColor:[UIColor blueColor] forState: UIControlStateNormal];
    //zoomSmallBtn.frame = CGRectMake(zoomLargeBtn.frame.origin.x, CGRectGetMaxY(zoomLargeBtn.frame) + 20, 40, 30);
    [zoomSmallBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(zoomLargeBtn);
        make.top.mas_equalTo(zoomLargeBtn.bottom);
        make.size.mas_equalTo(zoomLargeBtn);
        
    }];
    [zoomSmallBtn setImage:[UIImage imageNamed:@"zoomSmall"] forState:UIControlStateNormal];
    zoomSmallBtn.backgroundColor = [UIColor whiteColor];
    
    [zoomSmallBtn addTarget:self action:@selector(zoomButtonAction:) forControlEvents:UIControlEventTouchUpInside];
   
   
    
    

}

-(void)zoomButtonAction:(UIButton *)button{
    if (button.tag == 1000) {
        CGFloat level = self.mapView.zoomLevel;
        
        [self.mapView setZoomLevel:level + 1 animated:YES];
//        [self.mapView setZoomLevel:level + 0.3 atPivot:self.mapView.userLocation animated:YES];
        
    }else{
        
        CGFloat level = self.mapView.zoomLevel;
        
        [self.mapView setZoomLevel:level - 1 animated:YES];

    
    }

}

//创建定位按钮
-(void)initLocationButton{
    self.locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.locationButton.frame = CGRectMake(20, CGRectGetHeight(self.mapView.bounds) - 90, 30, 30);
    self.locationButton.layer.masksToBounds = YES;
    self.locationButton.layer.cornerRadius = 5;
    
    [self.locationButton addTarget:self action:@selector(locateAction) forControlEvents:UIControlEventTouchUpInside];
    [self.locationButton setImage:[UIImage imageNamed:@"location_yes@2x"] forState:UIControlStateNormal];
    [self.mapView addSubview:self.locationButton];
    
}

//开启或关闭定位
-(void)locateAction{
    if (self.mapView.userTrackingMode != MAUserTrackingModeFollow) {
        [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    }else{
        [self.mapView setUserTrackingMode:MAUserTrackingModeNone animated:YES];
        
    }
    
}

//替换定位按钮图标:使用mapView回调方法监听定位模式状态
-(void)mapView:(MAMapView *)mapView didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated{
    if (mode ==  MAUserTrackingModeNone) {
        [self.locationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    }else{
        
        [self.locationButton setImage:[UIImage imageNamed:@"location_yes"]forState:UIControlStateNormal];
        
    }
}


//****************附近搜索*********************

//初始化搜索tableView
-(void)initTableView{
    
    CGFloat tableHeight = CGRectGetHeight(self.view.bounds) * 0.5;
    self.resultTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, self.mapView.frame.origin.y, CGRectGetWidth(self.view.bounds), tableHeight) style:UITableViewStylePlain];
    self.resultTableview.delegate = self;
    self.resultTableview.dataSource = self;
    [self.view addSubview:self.resultTableview];
    [self.resultTableview release];
    self.resultTableview.backgroundColor = [UIColor whiteColor];
    self.resultTableview.hidden = YES;
    
    
}

//设置搜索数组等
-(void)initAttributes{
    //self.annotations = [NSMutableArray array];
    self.poisArray = nil;
    
    //添加长按手势
    self.longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    self.longPress.delegate = self;
    [self.mapView addGestureRecognizer:self.longPress];
    [self.longPress release];
    
}

//设置附近搜索按钮
-(void)initSearchBtn{
    UIButton *searchButton = [UIButton buttonWithType: UIButtonTypeCustom];
    searchButton.frame = CGRectMake(self.view.frame.size.width - 80, self.searchTextField.frame.origin.y + 5, 80, 30);
    searchButton.layer.masksToBounds = YES;
    [searchButton setTitle:@"搜索周边" forState:UIControlStateNormal];
    //[searchButton setImage:[UIImage imageNamed:@"search"] forState:   UIControlStateNormal];
    [searchButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    searchButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [searchButton addTarget:self action:@selector(searchAction) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:searchButton];
    
}

//搜索按钮执行方法
-(void)searchAction{
    //当前位置为空或者搜索未初始化
    if (self.currentlocation == nil || self.search == nil||self.searchTextField.text.length == 0) {
        NSLog(@"搜索失败");
        return;
    }
    
    
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:self.currentlocation.coordinate.latitude longitude:self.currentlocation.coordinate.longitude];
    request.keywords = self.searchTextField.text;
    
    request.types = @"餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅";
    //搜索排序顺序
    request.sortrule = 0;
    //是否显示扩展信息
    request.requireExtension = YES;
    //搜索的半径  (默认范围是三千米)
    request.radius = 4000;
    
    [self.searchTextField resignFirstResponder];
    
    //发起周边搜索
    [self.search AMapPOIAroundSearch:request];
    [request release];
    
    //显示tableview
    self.resultTableview.hidden = NO;
    
    
}

//实现POI搜索对应的回调函数 在搜索回调方法中得到搜索结果
-(void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    
    if(response.pois.count == 0){
        return;
    }
    
    if (response.pois.count > 0) {
        self.poisArray = response.pois;
        
        
        if (self.destinationPoint != nil) {
            //清除以前的标注
            [self.mapView removeAnnotation:self.destinationPoint];
            self.destinationPoint = nil;
            
            [self.mapView removeOverlays:self.pathPolylines];
            self.pathPolylines = nil;
            
        }
        
        
        [self.resultTableview reloadData];
        
        
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.poisArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:cellIdentifier];
    }
    
    
    AMapPOI *poi = [self.poisArray objectAtIndex:indexPath.row];
    cell.textLabel.text = poi.name;
    cell.detailTextLabel.text = poi.address;
    
    return cell;
    
}

//点击创建标注 得到annotation坐标
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.destinationPoint != nil) {
        //清除以前的标注
        [self.mapView removeAnnotation:self.destinationPoint];
        self.destinationPoint = nil;
        
        [self.mapView removeOverlays:self.pathPolylines];
        self.pathPolylines = nil;
        
    }
    
    
    
    AMapPOI *poi = [self.poisArray objectAtIndex:indexPath.row];
    self.destinationPoint = [[MAPointAnnotation alloc] init];
    self.destinationPoint.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
    self.destinationPoint.title = poi.name;
    self.destinationPoint.subtitle = poi.address;
    [self.mapView addAnnotation:self.destinationPoint];
    //将显示的中心切换到长按的地方
    // b) 设置缩放
    MACoordinateSpan span = MACoordinateSpanMake(0.01, 0.01);
    
    // c) 设置区域
    MACoordinateRegion region = MACoordinateRegionMake(self.destinationPoint.coordinate, span);
    // d) 显示区域
    _mapView.region = region;

    
    [_destinationPoint release];
    [self.searchTextField resignFirstResponder];
    self.resultTableview.hidden = YES;
    
}


//在MAMapView的回调函数中,取得或创建annotationView,并配置annotationView的属性
-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationIndetifier];
        if (annotationView == nil) {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationIndetifier];
            //aaaaaaaaaaaaaa
        }
        annotationView.canShowCallout = YES;
        annotationView.animatesDrop = YES;

        return annotationView;
    }
    return nil;
    
}

//******************路线规划***********************

//长按手势方法
-(void)longPressAction:(UILongPressGestureRecognizer *)longPress{
    
    if (longPress.state == UIGestureRecognizerStateBegan) {
        /*!
         @brief 将指定view坐标系的坐标转换为经纬度 @param point 指定view坐标系的坐标 @param view 指定的view
         @return 经纬度
         */
        CLLocationCoordinate2D coordinate = [self.mapView convertPoint:[longPress locationInView:self.mapView] toCoordinateFromView:self.mapView];
        if (self.destinationPoint != nil) {
            //清除以前的标注
            [self.mapView removeAnnotation:self.destinationPoint];
            self.destinationPoint = nil;
            
            [self.mapView removeOverlays:self.pathPolylines];
            self.pathPolylines = nil;
            
        }
        self.destinationPoint = [[MAPointAnnotation alloc] init];
        self.destinationPoint.coordinate = coordinate;
        
        [self.mapView addAnnotation:self.destinationPoint];
        [_destinationPoint release];
        
    }
    
}

//设置路线规划按钮
-(void)initPathBtn{
    UIButton *pathButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    pathButton.frame = CGRectMake(self.mapView.compassOrigin.x, self.mapView.compassOrigin.y + 60, 30, 30);
    pathButton.layer.masksToBounds = YES;
    pathButton.backgroundColor = [UIColor whiteColor];
    [pathButton setImage:[[UIImage imageNamed:@"path"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    pathButton.imageView.frame = pathButton.frame;
    [pathButton addTarget:self action:@selector(pathAction)
         forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:pathButton];
    
}

//路线按钮点击方法
-(void)pathAction{
    if (_destinationPoint == nil || _currentlocation == nil || _search == nil)
    {
        NSLog(@"路线规划失败");
        return; }
    //创建步行路径规划请求对象
    AMapWalkingRouteSearchRequest *request = [[AMapWalkingRouteSearchRequest alloc] init];
    
    request.origin = [AMapGeoPoint locationWithLatitude:self.currentlocation.coordinate.latitude longitude:self.currentlocation.coordinate.longitude];
    
    request.destination = [AMapGeoPoint locationWithLatitude:self.destinationPoint.coordinate.latitude longitude:self.destinationPoint.coordinate.longitude];
    
    //进行查询
    [self.search AMapWalkingRouteSearch:request];
    [request release];
}

//实现路径搜索的回调函数 获取搜索结果
-(void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
    if(response.route == nil){
        return;
    }
    
    //清空覆盖物
    if (response.count > 0) {
        //overrlays是覆盖物,polylines继承于overlay,可加载到地图上(还有标注)
        [self.mapView removeOverlays:self.pathPolylines];
        self.pathPolylines = nil;
    }
    //只显示第一条
    self.pathPolylines = [self polylinesForPath:response.route.paths[0]];
    [self.mapView addOverlays:self.pathPolylines];
    
    [self.mapView showAnnotations:@[self.destinationPoint,self.mapView.userLocation] animated:YES];
}

//路线解析方法
-(NSArray *)polylinesForPath:(AMapPath *)path{
    if (path == nil || path.steps.count == 0) {
        return nil;
    }
    NSMutableArray *polylines = [NSMutableArray array];
    //遍历每一个step
    [path.steps enumerateObjectsUsingBlock:^(AMapStep *step, NSUInteger idx, BOOL * _Nonnull stop) {
        NSUInteger count = 0;
        CLLocationCoordinate2D *coordinates = [self coordinatesForString:step.polyline coordinateCount:&count parseToken:@";"];
        
        //根据经纬度坐标生成多线段
        MAPolyline *polyline = [MAPolyline polylineWithCoordinates:coordinates count:count];
        [polylines addObject:polyline];
        free(coordinates),coordinates = NULL;
    }];
    
    return polylines;
    
}

//解析经纬度字符串

- (CLLocationCoordinate2D *)coordinatesForString:(NSString *)string
                                 coordinateCount:(NSUInteger *)coordinateCount parseToken:(NSString *)token{
    if (string == nil){
        return NULL;
    }
    if (token == nil){
        token = @",";
    }
    NSString *str = @"";
    if (![token isEqualToString:@","]) {
        str = [string stringByReplacingOccurrencesOfString:token withString:@","];
    }else{
        str = [NSString stringWithString:string];
    }
    NSArray *components = [str componentsSeparatedByString:@","];
    NSUInteger count = [components count] / 2;
    if (coordinateCount != NULL) {
        *coordinateCount = count;
    }
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D *)malloc(count * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i < count; i++) {
        coordinates[i].longitude = [[components objectAtIndex:2 * i]doubleValue];
        coordinates[i].latitude = [[components objectAtIndex:2 * i + 1]doubleValue];
    }
    return coordinates;
    
}

//在获取并解析搜索结果后,添加polyline到地图
-(MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay{
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        MAPolylineRenderer *polylineRe = [[MAPolylineRenderer alloc] initWithOverlay:overlay];
        polylineRe.strokeColor = [UIColor blueColor];
        polylineRe.lineWidth = 4;
        
        return polylineRe;
        
    }
    
    return nil;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
